import router, { asyncRoutes } from './router'
import store from './store'
import { RouteRecordRaw } from 'vue-router'
import { usePermissionStore } from './store/modules/permission'
import { useUserStore } from './store/modules/user'

// 权限白名单，无需登录即可访问
const whiteList = ['/login', '/404', '/403']

/**
 * 根据权限过滤路由
 * @param routes 路由
 * @param permissions 权限
 */
export function filterAsyncRoutes(routes: RouteRecordRaw[], permissions: string[]): RouteRecordRaw[] {
  const res: RouteRecordRaw[] = []
  
  routes.forEach(route => {
    const tmp = { ...route }
    
    // 检查是否有权限访问该路由
    if (hasPermission(tmp, permissions)) {
      // 如果有子路由，递归过滤
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, permissions)
      }
      res.push(tmp)
    }
  })
  
  return res
}

/**
 * 检查是否有权限
 * @param route 路由
 * @param permissions 权限
 */
function hasPermission(route: RouteRecordRaw, permissions: string[]): boolean {
  if (route.meta && route.meta.permissions) {
    // 超级管理员拥有所有权限
    if (permissions.includes('*')) {
      return true
    }
    // 检查是否有权限
    return permissions.some(permission => {
      if (Array.isArray(route.meta!.permissions)) {
        return (route.meta!.permissions as string[]).includes(permission)
      }
      return false
    })
  }
  // 如果没有设置权限，则默认允许访问
  return true
}

/**
 * 初始化权限
 */
export async function initPermission() {
  const permissionStore = usePermissionStore()
  const userStore = useUserStore()
  
  try {
    // 获取用户信息和权限
    const { permissions } = await userStore.getUserInfo()
    
    // 根据权限过滤路由
    const accessRoutes = filterAsyncRoutes(asyncRoutes, permissions)
    
    // 添加动态路由
    accessRoutes.forEach(route => {
      router.addRoute(route)
    })
    
    // 存储路由到store
    permissionStore.setRoutes(accessRoutes)
    
    return accessRoutes
  } catch (error) {
    console.error('初始化权限失败:', error)
    return []
  }
}

// 全局路由权限控制
router.beforeEach(async (to, from, next) => {
  // 白名单直接放行
  if (whiteList.includes(to.path)) {
    return next()
  }
  
  const userStore = useUserStore()
  const permissionStore = usePermissionStore()
  
  // 检查是否已登录
  if (userStore.token) {
    // 检查是否已加载权限路由
    if (permissionStore.routes.length === 0) {
      // 初始化权限
      await initPermission()
      
      // 如果当前路由不存在，重定向到首页
      if (to.matched.length === 0) {
        next({ path: '/', replace: true })
      } else {
        next({ ...to, replace: true })
      }
    } else {
      next()
    }
  } else {
    next(`/login?redirect=${to.path}`)
  }
}) 